package com.liangxy.news.database;

import android.content.Context;
import android.util.Log;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;

import java.io.File;

import com.liangxy.news.model.News;
import com.liangxy.news.model.NewsDetail;
import com.liangxy.news.model.User;
import com.liangxy.news.model.UserFollowNews;
import com.liangxy.news.model.UserHistory;

/**
 * Room database for the app
 */
@Database(entities = {
        News.class, 
        User.class, 
        UserHistory.class, 
        NewsDetail.class, 
        UserFollowNews.class
        }, 
        version = 2, 
        exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
    
    // Singleton instance
    private static AppDatabase INSTANCE;
    // 添加数据库名称常量
    private static final String DATABASE_NAME = "news_database";
    
    /**
     * Get database instance
     * @param context Application context
     * @return AppDatabase instance
     */
    public static AppDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    try {
                        Context applicationContext = context.getApplicationContext();
                        
                        // 检查并删除可能存在的损坏数据库
                        checkAndDeleteCorruptedDatabase(applicationContext);
                        
                        INSTANCE = Room.databaseBuilder(
                                applicationContext,
                                AppDatabase.class,
                                DATABASE_NAME
                        )
                        .fallbackToDestructiveMigration()
                        .setJournalMode(RoomDatabase.JournalMode.WRITE_AHEAD_LOGGING) // 使用WAL模式提高性能和可靠性
                        .allowMainThreadQueries() // 在正式环境中应避免在主线程中查询数据库
                        .build();
                        Log.d("AppDatabase", "Database instance created successfully");
                    } catch (Exception e) {
                        Log.e("AppDatabase", "Error creating database instance: " + e.getMessage(), e);
                        throw e;
                    }
                }
            }
        }
        return INSTANCE;
    }
    
    /**
     * 检查并删除可能损坏的数据库文件
     * @param context 应用上下文
     */
    private static void checkAndDeleteCorruptedDatabase(Context context) {
        try {
            // 数据库文件路径
            File dbFile = context.getDatabasePath(DATABASE_NAME);
            File dbShm = new File(dbFile.getParent(), DATABASE_NAME + "-shm");
            File dbWal = new File(dbFile.getParent(), DATABASE_NAME + "-wal");
            
            // 如果数据库文件存在但无法访问，则删除
            if (dbFile.exists() && (!dbFile.canRead() || !dbFile.canWrite())) {
                Log.w("AppDatabase", "Found corrupted database file, deleting: " + dbFile.getAbsolutePath());
                dbFile.delete();
                if (dbShm.exists()) dbShm.delete();
                if (dbWal.exists()) dbWal.delete();
            }
        } catch (Exception e) {
            Log.e("AppDatabase", "Error checking database file: " + e.getMessage(), e);
        }
    }
    
    /**
     * 关闭数据库连接
     */
    public static void closeDatabase() {
        if (INSTANCE != null && INSTANCE.isOpen()) {
            try {
                // 确保将写入缓存的数据同步到数据库文件
                INSTANCE.getOpenHelper().getWritableDatabase().execSQL("PRAGMA wal_checkpoint(FULL)");
                INSTANCE.close();
                INSTANCE = null;
                Log.d("AppDatabase", "Database closed successfully");
            } catch (Exception e) {
                Log.e("AppDatabase", "Error closing database: " + e.getMessage(), e);
            }
        }
    }
    
    // DAOs
    public abstract NewsDao newsDao();
    public abstract UserDao userDao();
    public abstract HistoryDao historyDao();
    public abstract NewsDetailDao newsDetailDao();
    public abstract UserFollowNewsDao userFollowNewsDao();
} 